let pages = document.getElementsByClassName('page')
let pageNumberElement = document.getElementById('pagenumber')
let pageCount = pages.length
let activePage = 0
let autoPlay = true

function updateActivePage() {
	for (let i = 0; i < pageCount; ++i) {
		let page = pages[i]
		if (i == activePage)
			page.classList.remove('hidden')
		else
			page.classList.add('hidden')
	}
	if (pageNumberElement)
		pageNumberElement.innerText = (activePage + 1) + ' / ' + pageCount
	let id = pages[activePage].getAttribute('type')
	if (!id)
		id = pages[activePage].id
	if (id) {
		let config = pageConfig[id]
		if (config.init)
			config.init()
		if (autoPlay && config.duration)
			setTimeout(nextPage, config.duration)
	}
}

let searchPage = parseInt(window.location.search.substring(1))
if (searchPage >= 0 && searchPage < pageCount) {
	activePage = searchPage
	autoPlay = false
}
updateActivePage()

function prevPage() {
	if (!activePage)
		activePage = pageCount
	--activePage
	updateActivePage()
}
function nextPage() {
	if ((++activePage) == pageCount)
		activePage = 0
	updateActivePage()
}

document.addEventListener('keydown', function (event) {
	if (event.code == marbleRaceConfig.nextPageKeyCode)
		nextPage()
	else if (event.code == marbleRaceConfig.prevPageKeyCode)
		prevPage()
})
document.addEventListener('click', function (event) {
	nextPage()
})
document.addEventListener('touchend', function (event) {
	nextPage()
})